﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace CommHelper
{
    public sealed class XmlHelper
    {
        /// <summary>  
        /// 反序列化XML字符串为指定类型  
        /// </summary>  
        public static object Deserialize<T>(string xml)
        {
            FileStream fs = null;
            try
            {
                fs = new FileStream(xml, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                return serializer.Deserialize(fs);
            }
            catch (Exception innerException)
            {
                LogHelper.WriteErrorLog(string.Format("Couldn't parse XML: '{0}'; {1};{2}", xml, typeof(T).FullName, innerException));
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
            return null;
        }

        /// <summary>  
        /// 序列化object对象为XML字符串  
        /// </summary>  
        public static void Serialize<T>(object ObjectToSerialize, string filename)
        {
            FileStream fs = null;
            try
            {
                fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(fs, ObjectToSerialize);
            }
            catch (Exception innerException)
            {
                throw new ApplicationException("Couldn't Serialize Object:" + typeof(T).Name, innerException);
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
        }
    }
}
